package com.cyz.common.security;

import com.cyz.common.bean.User;
import com.cyz.common.enums.MyEnums;
import com.cyz.common.exception.MyException;
import com.cyz.common.service.MenuService;
import com.cyz.common.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询数据库
        User user = userService.getByUsername(username);
        //没有查到
        if(ObjectUtils.isEmpty(user)){
            throw new MyException(MyEnums.LOGIN_ERROR);
        }
        //如果用户是后端用户，查询权限封装
        if(user.getType().equals(MyEnums.USER_TYPE_ADMIN)){
            List<String> list = menuService.queryMenusByUserId(user.getId());
            return new MyUserDetails(user,list);
        }
        //否则权限返回为空
        return new MyUserDetails(user,null);
    }

}
